package com.shengdou.as.slopsapptest.Fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.shengdou.as.slopsapptest.Activity.FailureQuestionActivity;
import com.shengdou.as.slopsapptest.R;
import com.shengdou.as.slopsapptest.base.BaseFragment;
import com.shengdou.as.slopsapptest.bean.AlarmListBean;
import com.shengdou.as.slopsapptest.bean.PoolDataBean;
import com.shengdou.as.slopsapptest.bean.poolChartDayBean;
import com.shengdou.as.slopsapptest.utils.Constants;
import com.shengdou.as.slopsapptest.utils.DateUtils;
import com.shengdou.as.slopsapptest.utils.FileUtils;
import com.shengdou.as.slopsapptest.utils.HttpUtils;
import com.shengdou.as.slopsapptest.utils.LogUtil;
import com.shengdou.as.slopsapptest.utils.MyListViewUtils;
import com.shengdou.as.slopsapptest.utils.NetConstant;
import com.shengdou.as.slopsapptest.utils.SharedPreferenceUtil;
import com.shengdou.as.slopsapptest.utils.ToastUtils;
import com.shengdou.as.slopsapptest.view.MyChartView;
import com.shengdou.as.slopsapptest.view.MyImageViewSingle;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by AS on 2016/11/26.
 * 首页次级页面
 */

public class PoolTabFragment extends BaseFragment {
    private boolean selectData;
    private ImageView back;
    private TextView mTxtPool;
    private TextView mTxtQuestion;
    private TextView mTxtWeekInfo;//7天数据备注
    private TextView mTxtCleanWrite;
    private long s;
    private PopupWindow popup = null;
    private MyChartView myChartView;
    private MyImageViewSingle myImageView;
    private TextView mTxtHeigh, mTxtStaus, mTxtType;
    private ArrayList<Float> datas = new ArrayList<>();
    private ArrayList<Float> Weekdatas = new ArrayList<>();
    private ArrayList<poolChartDayBean.DataBean> Pooldata = new ArrayList<>();
    private ArrayList<poolChartDayBean.DataBean> Pooldatas = new ArrayList<>();
    private MyListViewUtils myListViewUtils;
    private RadioButton mRadioTime, mRadioWeek;
    private String[] num;
    private String[] weekNum;
    private String[] WeekDate;
    private float height = 0;
    private int alarm;
    private float w, h;
    private String timestamp;//获得的时间戳
    private ArrayList<AlarmListBean.DataBean> arrayList;
    private MyAdapter adapter;
    int pools_id;
    private String pool_name;
    private ArrayList<PoolDataBean.DataBean> mArray;
    private boolean isselect;
    private Map<String, String> params = new HashMap<>();
    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.ALARMLIST:
                    //报警记录信息
                    String result = msg.obj.toString();
                    LogUtil.e("result", result);
                    LogUtil.e("pools_id11", params.get("pools_id"));
                    adapter = null;
                    arrayList = new ArrayList<>();
                    AlarmListBean managerInfo = new Gson().fromJson(result, AlarmListBean.class);
                    arrayList.addAll(managerInfo.getData());
                    LogUtil.e("arrayList.size()", arrayList.size() + "");
                    if (adapter == null) {
                        adapter = new MyAdapter(arrayList);
                        myListViewUtils.setAdapter(adapter);
                        if (arrayList.size() != 0) {
                            myListViewUtils.setVisibility(View.VISIBLE);
                        } else {
                            LogUtil.e("arrayList.size()", arrayList.size() + "");
                            myListViewUtils.setVisibility(View.GONE);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    //一周
                    HttpUtils.postParmas(mHandler, NetConstant.POOLWEEK(), params, Constants.POOLWEEK, getActivity());
                    break;
                case Constants.POOLDAY:
                    //24小时折线的数据信息首次请求
                    String results = msg.obj.toString();
                    LogUtil.e("result", results);
                    try {
                        JSONObject jsonObject = new JSONObject(results);
                        String data = jsonObject.getString("data");
                        LogUtil.e("data", data);
                        if (!data.equals("false")) {
                            poolChartDayBean mPoolChartDayBean = new Gson().fromJson(results, poolChartDayBean.class);
                            datas.clear();
                            Pooldata.addAll(mPoolChartDayBean.getData());
                            num = new String[mPoolChartDayBean.getData().size()];
                            Collections.reverse(mPoolChartDayBean.getData());//倒序
                            for (int i = 0; i < mPoolChartDayBean.getData().size(); i++) {
                                datas.add(mPoolChartDayBean.getData().get(i).getHeight());
//                                num[0] = "0";
                                num[i] = DateUtils.stringIntTime(mPoolChartDayBean.getData().get(i).getCreate_time());

                            }
                            myChartView.setColumnInfo(datas);
                            myChartView.setXNum(num);

                        } else {
                            datas.clear();
                            myChartView.setColumnInfo(datas);
                            myChartView.setXNum(null);
                        }
                        myChartView.setXDateNum(null);
                        params.put("id", pools_id + "");
                        LogUtil.e("pools_ididdddddddddddddddddddd", pools_id + "");
                        //单水池实时数据接口
                        HttpUtils.postParmas(mHandler, NetConstant.SINGLETIME(), params, Constants.SINGLETIME, getActivity());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case Constants.POOLWEEK:
                    //一周的折线首次请求数据
                    String resultss = msg.obj.toString();
                    LogUtil.e("result", resultss);
                    try {
                        JSONObject jsonObject = new JSONObject(resultss);
                        String data = jsonObject.getString("data");
                        LogUtil.e("data一周实时数据", data);
                        if (!data.equals("false")) {
                            poolChartDayBean mPoolChartDayBeans = new Gson().fromJson(resultss, poolChartDayBean.class);
                            Weekdatas.clear();
                            Pooldatas.clear();
                            Pooldatas.addAll(mPoolChartDayBeans.getData());
                            weekNum = new String[mPoolChartDayBeans.getData().size()];
                            WeekDate = new String[mPoolChartDayBeans.getData().size()];
//                    Collections.reverse(mPoolChartDayBeans.getData());//倒序
                            for (int i = 0; i < mPoolChartDayBeans.getData().size(); i++) {
                                Weekdatas.add(mPoolChartDayBeans.getData().get(i).getHeight());
//                                weekNum[0] = "0";
//                                WeekDate[0] = "2016-01-01";
                                weekNum[i] = DateUtils.stringIntTime(mPoolChartDayBeans.getData().get(i).getCreate_time());
                                WeekDate[i] = DateUtils.stringFormateMMDD(mPoolChartDayBeans.getData().get(i).getCreate_time());

                            }
                           /* myChartView.setColumnInfo(Weekdatas);
                            myChartView.setXNum(weekNum);
                            myChartView.setXDateNum(WeekDate);*/
                        } else {
                            Weekdatas.clear();
                            myChartView.setColumnInfo(Weekdatas);
                            myChartView.setXNum(null);
                            myChartView.setXDateNum(null);
                        }
                        //24小时
                        HttpUtils.postParmas(mHandler, NetConstant.POOLDAY(), params, Constants.POOLDAY, getActivity());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case Constants.POOLDAYS:
                    //24小时折线的数据信息
                    String poolResult = msg.obj.toString();
                    LogUtil.e("poolResult", poolResult);
                    try {
                        JSONObject jsonObject = new JSONObject(poolResult);
                        String data = jsonObject.getString("data");
                        if (!data.equals("false")) {
                            poolChartDayBean poolChartDayBean = new Gson().fromJson(poolResult, poolChartDayBean.class);
                            datas.clear();
                            Pooldata.clear();
                            Pooldata.addAll(poolChartDayBean.getData());
                            num = new String[poolChartDayBean.getData().size()];
                            Collections.reverse(poolChartDayBean.getData());//倒序
                            for (int i = 0; i < poolChartDayBean.getData().size(); i++) {
                                datas.add(poolChartDayBean.getData().get(i).getHeight());
//                                num[0] = "0";
                                num[i] = DateUtils.stringIntTime(poolChartDayBean.getData().get(i).getCreate_time());
                            }
                            myChartView.setColumnInfo(datas);
                            myChartView.setXNum(num);
                        } else {
                            datas.clear();
                            myChartView.setColumnInfo(datas);
                            myChartView.setXNum(null);
                        }
                        myChartView.setXDateNum(null);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case Constants.POOLWEEKS:
                    //一周的折线数据
                    String weekResult = msg.obj.toString();
                    LogUtil.e("weekResult", weekResult);
                    try {
                        JSONObject jsonObject = new JSONObject(weekResult);
                        String data = jsonObject.getString("data");
                        if (!data.equals("false")) {
                            poolChartDayBean mPoolWeekDay = new Gson().fromJson(weekResult, poolChartDayBean.class);
                            Weekdatas.clear();
                            Pooldatas.clear();
                            Pooldatas.addAll(mPoolWeekDay.getData());
                            weekNum = new String[mPoolWeekDay.getData().size()];
                            WeekDate = new String[mPoolWeekDay.getData().size()];
//                    Collections.reverse(mPoolWeekDay.getData());//倒序
                            for (int i = 0; i < mPoolWeekDay.getData().size(); i++) {
                                Weekdatas.add(mPoolWeekDay.getData().get(i).getHeight());
//                                weekNum[0] = "0";
//                                WeekDate[0] = "2016-01-01";
                                weekNum[i] = DateUtils.stringIntTime(mPoolWeekDay.getData().get(i).getCreate_time());
                                WeekDate[i] = DateUtils.stringFormateMMDD(mPoolWeekDay.getData().get(i).getCreate_time());
                                LogUtil.e("mPoolWeekDay.getData().get(i - 1).getCreate_time()", mPoolWeekDay.getData().get(i).getCreate_time() + "");
                            }
                            LogUtil.e("Weekdatas.size", Weekdatas.size() + "");
                            for (int i = 0; i < WeekDate.length; i++) {
                                LogUtil.e("WeekDate", WeekDate[i] + "");

                            }
                            myChartView.setColumnInfo(Weekdatas);
                            myChartView.setXNum(weekNum);
                            myChartView.setXDateNum(WeekDate);
                        } else {
                            Weekdatas.clear();
                            myChartView.setColumnInfo(Weekdatas);
                            myChartView.setXNum(null);
                            myChartView.setXDateNum(null);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case Constants.SENSOR:
                    //检测仪冲洗
                    String SENSOR = msg.obj.toString();
                    LogUtil.e("result", SENSOR);
                    try {
                        JSONObject jsonObject = new JSONObject(SENSOR);
                        String status = jsonObject.getString("status_text");
                        ToastUtils.showToast(status);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;
                case 4:
                    //池子的区分
                    mArray = (ArrayList<PoolDataBean.DataBean>) msg.obj;
                    LogUtil.e("mArray", mArray.size() + "");
                    break;
                case Constants.SINGLETIME:
                    //单水池实时数据接口
                    String responeResult = msg.obj.toString();
                    LogUtil.e("单水池实时数据接口", responeResult);
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(responeResult);
                        int status = jsonObject.getInt("status");
                        if (status == 201) {
                            height = 0;
                            alarm = -1;
                            mTxtStaus.setText("系统离线");
                            mTxtCleanWrite.setClickable(false);
                        } else if (status == 1) {
                            height = (float) jsonObject.getDouble("height");
                            alarm = jsonObject.getInt("alarm");
                            mTxtStaus.setText("系统在线");
                            mTxtCleanWrite.setClickable(true);
                        } else if (status == 200) {
                            height = (float) jsonObject.getDouble("height");
                            alarm = jsonObject.getInt("alarm");
                            mTxtStaus.setText("自动清洗");
                            mTxtCleanWrite.setClickable(false);
                        } else if (status == 202) {
                            height = (float) jsonObject.getDouble("height");
                            alarm = jsonObject.getInt("alarm");
                            mTxtStaus.setText("系统故障");
                            mTxtCleanWrite.setClickable(true);
                        }
                        timestamp = jsonObject.getString("timestamp");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (height >= 0) {
                        mTxtHeigh.setText("泥位" + height + "米");
                    } else {
                        mTxtHeigh.setText("泥位0.0米");
                    }
                    if (alarm == 0) {
                        mTxtType.setText("正常");
                        mTxtType.setTextColor(getResources().getColor(R.color.green));
                    } else if (alarm == 1) {
                        mTxtType.setText("橙色报警");
                        mTxtType.setTextColor(getResources().getColor(R.color.orange));
                    } else if (alarm == 2) {
                        mTxtType.setText("红色报警");
                        mTxtType.setTextColor(getResources().getColor(R.color.red));
                    }
                    myImageView.setWind(height, alarm);
                    if (selectData == true) {

                        new Thread(new Runnable() {
                            public void run() {
                                params.put("id", pools_id + "");
                                params.put("timestamp", timestamp);
                                HttpUtils.postParmas(mHandler, NetConstant.SINGLETIME(), params, Constants.SINGLETIME, getActivity());
                            }
                        }).start();
                    }
                    break;
            }
        }
    };

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.activity_pool_tab, null);
    }

    @Override
    protected void initFindViewById(View view) {
        mTxtWeekInfo = (TextView) view.findViewById(R.id.txt_week_info);
        myImageView = (MyImageViewSingle) view.findViewById(R.id.img);
        mTxtHeigh = (TextView) view.findViewById(R.id.txt_seat);
        mTxtStaus = (TextView) view.findViewById(R.id.txt_type);
        mTxtType = (TextView) view.findViewById(R.id.txt_status);
        myChartView = (MyChartView) view.findViewById(R.id.ChartView);
        myListViewUtils = (MyListViewUtils) view.findViewById(R.id.listview);
        mRadioTime = (RadioButton) view.findViewById(R.id.txt_time);
        mRadioWeek = (RadioButton) view.findViewById(R.id.txt_week);
        back = (ImageView) view.findViewById(R.id.back);
        mTxtPool = (TextView) view.findViewById(R.id.txt_pools);
        back.setOnClickListener(this);
        mTxtQuestion = (TextView) view.findViewById(R.id.txt_find);
        mTxtCleanWrite = (TextView) view.findViewById(R.id.txt_clean_write);
        mTxtCleanWrite.setOnClickListener(this);
        mTxtQuestion.setOnClickListener(this);
        mTxtPool.setOnClickListener(this);
        mRadioTime.setOnClickListener(this);
        mRadioWeek.setOnClickListener(this);
    }

    @Override
    public void initData() {
        pools_id = getArguments().getInt("pools_id");
        if (getDataTime() < 30) {
            s = 30 - getDataTime();
            isselect = true;
            new Thread(new ClassCut()).start();// 开启倒计时
        } else {
            s = 30;
            mTxtCleanWrite.setText("检测仪冲洗");// 一轮倒计时结束 修改剩余时间为一分钟
        }
        selectData = true;
        LogUtil.e("initData==========PoolTabFragment===================", "initData");

        pool_name = getArguments().getString("pools_name");
        mTxtPool.setText(pool_name);
        params.put("pools_id", pools_id + "");
        //报警记录列表
        HttpUtils.post(mHandler, NetConstant.ALARMLIST(), params, Constants.ALARMLIST, getActivity());
        mTxtCleanWrite.setClickable(false);
    }

    @Override
    public void onPause() {
        super.onPause();
        LogUtil.e("onPause=========PoolTabFragment====================", "onPause");
//        OkHttpUtils.getInstance().cancelTag(NetConstant.SINGLETIME);
        selectData = false;
        OkHttpUtils.getInstance().cancelTag(NetConstant.SINGLETIME());//取消单水池实时数据接口请求
        LogUtil.e("selectData=====onPause=======", selectData + "");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        selectData = false;
        FileUtils.saveObject(getActivity(), "PoolDataBeans", null);
        LogUtil.e("selectData=====onDestroy=======", selectData + "");
    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtil.e("onStop========PoolTabFragment============", "onStop");
        selectData = false;
        LogUtil.e("selectData=====onStop=======", selectData + "");
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.e("onResume=====PoolTabFragment=========", "onResume");
        if (selectData == false) {
            selectData = true;
            //单水池实时数据接口
            HttpUtils.postParmas(mHandler, NetConstant.SINGLETIME(), params, Constants.SINGLETIME, getActivity());
        }
        LogUtil.e("selectData=====onResume=======", selectData + "");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                CheckFragment fragment = new CheckFragment();
                //调用上面的方法由 fragment1 跳转到 fragment2
                showFragment(PoolTabFragment.this, fragment);
                mTxtQuestion.setClickable(false);
                break;
            case R.id.txt_find:
                //故障申报
                Intent intent = new Intent(getActivity(), FailureQuestionActivity.class);
                intent.putExtra("pools_id", params.get("pools_id"));
                startActivity(intent);
                break;
            case R.id.txt_pools:
                showPopup();
                break;
            case R.id.txt_time:
                //24小时
                mTxtWeekInfo.setVisibility(View.GONE);
                mRadioTime.setBackgroundResource(R.drawable.shape_check_time_bg1);
                mRadioWeek.setBackgroundResource(R.drawable.shape_check_week_bg);
                mRadioTime.setTextColor(getResources().getColor(R.color.black));
                mRadioWeek.setTextColor(getResources().getColor(R.color.white));
                myChartView.setColumnInfo(datas);
                myChartView.setXNum(num);
                myChartView.setXDateNum(null);
                OkHttpUtils.getInstance().cancelTag(NetConstant.POOLWEEK());
                HttpUtils.postParmas(mHandler, NetConstant.POOLDAY(), params, Constants.POOLDAYS, getActivity());
                break;
            case R.id.txt_week:
                //7天
                mRadioWeek.setBackgroundResource(R.drawable.shape_check_week_bg1);
                mRadioTime.setBackgroundResource(R.drawable.shape_check_time_bg);
                mRadioTime.setTextColor(getResources().getColor(R.color.white));
                mRadioWeek.setTextColor(getResources().getColor(R.color.black));
                myChartView.setColumnInfo(Weekdatas);
                myChartView.setXNum(weekNum);
                myChartView.setXDateNum(WeekDate);
                LogUtil.e("pools_id222", pools_id + "");
                OkHttpUtils.getInstance().cancelTag(NetConstant.POOLDAY());
                HttpUtils.postParmas(mHandler, NetConstant.POOLWEEK(), params, Constants.POOLWEEKS, getActivity());
                if (Weekdatas.size() == 0) {
                    mTxtWeekInfo.setVisibility(View.GONE);
                } else {
                    mTxtWeekInfo.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.txt_clean_write:
                //监测仪冲洗
                final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.show();
                alertDialog.getWindow().setContentView(R.layout.dialog_clean_write);
                alertDialog.getWindow().findViewById(R.id.dialog_verify_cancle).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        alertDialog.cancel();
                    }
                });
                alertDialog.getWindow().findViewById(R.id.dialog_verify_go).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        cleanWriteState();//开始冲洗
                        alertDialog.cancel();
                    }
                });

                break;
        }
    }

    private void cleanWriteState() {//开始冲洗
        //检测仪冲洗
        params.put("id", pools_id + "");
        params.put("code", "1001");
        LogUtil.e("pools_id检测仪冲洗", pools_id + "");
        LogUtil.e("systems", systems() + "");
        SharedPreferenceUtil.savePreferenceLong(getActivity(), "systems", systems());//保存时间
        if (getPoolDataBeans() == null) {
            if (getPoolDataBean() != null) {
                ArrayList<PoolDataBean.DataBean> arrayLists = new ArrayList<>();
                for (int i = 0; i < getPoolDataBean().size(); i++) {
                    PoolDataBean.DataBean poolDataBean = new PoolDataBean.DataBean();
                    if (getPoolDataBean().get(i).getId() == pools_id) {
                        poolDataBean.setTime(systems());
                        LogUtil.e("getPoolDataBean().get(i).getTime()", getPoolDataBean().get(i).getTime() + "");
                        LogUtil.e("getPoolDataBean().get(i).getId()", getPoolDataBean().get(i).getId() + "");
                    }
                    poolDataBean.setId(getPoolDataBean().get(i).getId());
                    poolDataBean.setName(getPoolDataBean().get(i).getName());
                    arrayLists.add(poolDataBean);
                }
                FileUtils.saveObject(getActivity(), "PoolDataBeans", arrayLists);
            }
        } else {
            ArrayList<PoolDataBean.DataBean> arrayLists = new ArrayList<>();
            for (int i = 0; i < getPoolDataBeans().size(); i++) {
                PoolDataBean.DataBean poolDataBean = new PoolDataBean.DataBean();
                if (getPoolDataBeans().get(i).getId() == pools_id) {
                    poolDataBean.setTime(systems());
                    poolDataBean.setId(getPoolDataBeans().get(i).getId());
                    poolDataBean.setName(getPoolDataBeans().get(i).getName());
                } else {
                    poolDataBean.setTime(getPoolDataBeans().get(i).getTime());
                    poolDataBean.setId(getPoolDataBeans().get(i).getId());
                    poolDataBean.setName(getPoolDataBeans().get(i).getName());
                }
                arrayLists.add(poolDataBean);
            }
            FileUtils.saveObject(getActivity(), "PoolDataBeans", arrayLists);
        }

        for (int i = 0; i < getPoolDataBeans().size(); i++) {
            LogUtil.e("getPoolDataBean().get(i).getTime()", getPoolDataBeans().get(i).getTime() + "");
            LogUtil.e("getPoolDataBean().get(i).getId()", getPoolDataBeans().get(i).getId() + "");
        }
        isselect = true;
        new Thread(new ClassCut()).start();// 开启倒计时
        LogUtil.e("检测仪冲洗所有的参数", params.get("code") + "---" + params.get("id") + "--" + params.get("pools_id"));
        HttpUtils.postParmas(mHandler, NetConstant.SENSOR(), params, Constants.SENSOR, getActivity());
    }

    public long systems() {//获取当前时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        long betton = 0;
        try {
            betton = formatter.parse(str).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return betton;
    }

    private void showPopup() {
        if (popup != null && popup.isShowing()) {
            popup.dismiss();
        } else {
            LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popview = inflater.inflate(R.layout.pop_list, null);
            ListView mListview = (ListView) popview.findViewById(R.id.listview);
            mListview.setAdapter(new mFactoryNameAdapter(mArray, popup));
            popup = new PopupWindow(popview, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            popup.setFocusable(true);
//          popup.setOutsideTouchable(true);
            popup.setBackgroundDrawable(new BitmapDrawable());

            popup.showAsDropDown(mTxtPool);

        }
    }

    public ArrayList<PoolDataBean.DataBean> getPoolDataBean() {
        ArrayList<PoolDataBean.DataBean> array;
        Object obj = FileUtils.getObject(getActivity(), "mArray");
        array = (ArrayList<PoolDataBean.DataBean>) obj;
        if (array != null) {
            return array;
        }
        return null;
    }

    public ArrayList<PoolDataBean.DataBean> getPoolDataBeans() {
        ArrayList<PoolDataBean.DataBean> array;
        Object obj = FileUtils.getObject(getActivity(), "PoolDataBeans");
        array = (ArrayList<PoolDataBean.DataBean>) obj;
        if (array != null) {
            return array;
        }

        return null;
    }

    public long getDataTime() {
        long oldtime = 0;
        if (getPoolDataBeans() != null) {
            for (int i = 0; i < getPoolDataBeans().size(); i++) {
                LogUtil.e("getPoolDataBean().get(i).getTime()", getPoolDataBeans().get(i).getTime() + "");
                LogUtil.e("getPoolDataBeans().get(i).getId()", getPoolDataBeans().get(i).getId() + "");
                LogUtil.e("pools_id", pools_id + "");
                if (getPoolDataBeans().get(i).getId() == pools_id) {
                    LogUtil.e("getPoolDataBeans().get(i).getId()", getPoolDataBeans().get(i).getId() + "");
                    if (getPoolDataBeans().get(i).getTime() != null) {
                        oldtime = getPoolDataBeans().get(i).getTime();
                        LogUtil.e("oldtime", oldtime + "");
                    }
                }
            }

        }
//        long oldtime = SharedPreferenceUtil.getPreferenceLong(getActivity(), "systems");
        long newTime = systems();
        long between = (newTime - oldtime) / 1000;
        LogUtil.e("between---------------", between + "oldtime--------------------" + oldtime);
        return between;
    }

    //报警记录
    private class MyAdapter extends BaseAdapter {
        private ArrayList<AlarmListBean.DataBean> mArray;

        public MyAdapter(ArrayList<AlarmListBean.DataBean> arrayList) {
            this.mArray = arrayList;
        }

        @Override
        public int getCount() {
            if (mArray.size() > 4) {
                return 3;
            } else {
                return mArray.size();
            }

        }

        @Override
        public Object getItem(int position) {
            return mArray.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(getActivity(), R.layout.item_water_info, null);
                holder.mTxtTime = (TextView) convertView.findViewById(R.id.txt_time);
                holder.mTxtDate = (TextView) convertView.findViewById(R.id.txt_date);
                holder.mTxtStatus = (TextView) convertView.findViewById(R.id.txt_status);
                holder.mTxtDistance = (TextView) convertView.findViewById(R.id.txt_distance);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mTxtTime.setText(DateUtils.stringFormateTime(mArray.get(position).getCreate_time()));//时间
            holder.mTxtDate.setText(DateUtils.stringFormateDate(mArray.get(position).getCreate_time()));//日期
            if (mArray.get(position).getChange_status() == -1) {
                holder.mTxtStatus.setText("下降");
            } else if (mArray.get(position).getChange_status() == 1) {

                holder.mTxtStatus.setText("上升");
            }
            holder.mTxtDistance.setText(mArray.get(position).getHeight() + "m");

//            holder.mTxtDistance.setText(mArray.get(position).getHeight() + "m");
            return convertView;
        }
    }

    class ViewHolder {
        TextView mTxtTime;
        TextView mTxtDate;
        TextView mTxtStatus;
        TextView mTxtDistance;
        //池子名称
        TextView mTxtName;
    }

    //池子名称
    private class mFactoryNameAdapter extends BaseAdapter {
        private ArrayList<PoolDataBean.DataBean> mArray;

        public mFactoryNameAdapter(ArrayList<PoolDataBean.DataBean> factoryArray, PopupWindow popup) {
            this.mArray = factoryArray;
        }

        @Override
        public int getCount() {
            return mArray.size();
        }

        @Override
        public Object getItem(int position) {
            return mArray.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mActivity, R.layout.item_factory_name, null);
                holder.mTxtName = (TextView) convertView.findViewById(R.id.pop_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.mTxtName.setText(mArray.get(position).getName());
            final int index = position;
            holder.mTxtName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isselect = false;
                    mRadioTime.setBackgroundResource(R.drawable.shape_check_time_bg1);
                    mRadioWeek.setBackgroundResource(R.drawable.shape_check_week_bg);
                    mRadioTime.setTextColor(getResources().getColor(R.color.black));
                    mRadioWeek.setTextColor(getResources().getColor(R.color.white));
                    mTxtPool.setText(mArray.get(index).getName());
                    //设置头部数据
                    mTxtHeigh.setText("泥位" + 0.0 + "米");
                    mTxtStaus.setText("系统离线");
                    mTxtCleanWrite.setClickable(false);
                    mTxtType.setText("");
                    myImageView.setWind(0, -1);
                    mTxtWeekInfo.setVisibility(View.GONE);
                    datas.clear();
                    Weekdatas.clear();
                    myChartView.setXNum(null);
                    height = 0;
                    if (pools_id != mArray.get(index).getId()) {
                        OkHttpUtils.getInstance().cancelTag(NetConstant.SINGLETIME());
                    }
                    pools_id = mArray.get(index).getId();
                    if (getDataTime() < 30) {
                        s = 30 - getDataTime();
                        isselect = true;
                        if (mTxtCleanWrite.getText().equals("检测仪冲洗")) {
                            new Thread(new ClassCut()).start();// 开启倒计时
                        }
                    } else {
                        s = 30;
                        mTxtCleanWrite.setText("检测仪冲洗");// 一轮倒计时结束 修改剩余时间为一分钟
                        if (mTxtStaus.getText().equals("系统离线")) {
                            mTxtCleanWrite.setClickable(false);
                        }
                    }
                    LogUtil.e("params", pools_id + "");
                    params.put("pools_id", pools_id + "");
                    //报警记录列表
                    HttpUtils.post(mHandler, NetConstant.ALARMLIST(), params, Constants.ALARMLIST, getActivity());
                    if (popup != null && popup.isShowing()) {
                        popup.dismiss();
                    }
                }
            });
            return convertView;
        }
    }

    /**
     * 公共方法： 从碎片fragment1跳转到碎片fragment2
     *
     * @param checkFragment   当前fragment
     * @param poolTabFragment 跳转后的fragment
     */
    public void showFragment(PoolTabFragment poolTabFragment, CheckFragment checkFragment) {
        selectData = false;
        mTxtQuestion.setClickable(false);
        mTxtPool.setClickable(false);
        OkHttpUtils.getInstance().cancelTag(NetConstant.SINGLETIME());
        // 获取 FragmentTransaction  对象
        FragmentTransaction transaction = getFragmentManager()
                .beginTransaction();
        //如果fragment2没有被添加过，就添加它替换当前的fragment1
        if (!checkFragment.isAdded()) {
            LogUtil.e("======checkFragment.isAdded()=============");
            transaction.add(R.id.fragment_container, checkFragment)
                    // 移除fragment1，即当前碎片
                    .remove(poolTabFragment)
                    //加入返回栈，这样你点击返回键的时候就会回退到fragment1了
                    .addToBackStack(null)
                    // 提交事务
                    .commitAllowingStateLoss();

        } else { //如果已经添加过了的话就隐藏fragment1，显示fragment2
            transaction
                    // 隐藏fragment1，即当前碎片
                    .hide(poolTabFragment)
                    // 显示已经添加过的碎片，即fragment2
                    .show(checkFragment)
                    // 加入返回栈
                    .addToBackStack(null)
                    // 提交事务
                    .commitAllowingStateLoss();
        }
    }

    class ClassCut implements Runnable {// 倒计时逻辑子线程

        @Override
        public void run() {
            // TODO Auto-generated method stub

            while (s > 0) {// 整个倒计时执行的循环
                s--;
                mHandler.post(new Runnable() {// 通过它在UI主线程中修改显示的剩余时间
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        if (isselect == true) {
                            mTxtCleanWrite.setText("检测仪冲洗" + s + "秒");// 显示剩余时间
                            mTxtCleanWrite.setClickable(false);
                        } else {
                            s = 0;
                        }
                    }
                });
                try {
                    Thread.sleep(1000);// 线程休眠一秒钟 这个就是倒计时的间隔时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            // 下面是倒计时结束逻辑
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    mTxtCleanWrite.setText("检测仪冲洗");// 一轮倒计时结束 修改剩余时间为一分钟
                    if (mTxtStaus.getText().equals("系统离线")) {
                        mTxtCleanWrite.setClickable(false);
                    } else {
                        mTxtCleanWrite.setClickable(true);
                    }
                    // Toast.makeText(MainActivity.this, "倒计时完成",
                    // Toast.LENGTH_LONG).show();//提示倒计时完成
                }
            });
            s = 30;// 修改倒计时剩余时间变量为60秒
        }
    }

}
